package com.freedom.rpc.thrift.client.socket;

import java.net.Socket;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 * MyTSocket池对象工厂
 * 
 * @author gqliu 2016年5月4日
 *
 */
public class TSocketFactory extends BasePooledObjectFactory<MyTSocket> {

	private String ip;
	private int port;

	public TSocketFactory(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}

	@Override
	public MyTSocket create() throws Exception {		
		MyTSocket socket = new MyTSocket(ip, port);
		socket.open();
		return socket;
	}

	@Override
	public PooledObject<MyTSocket> wrap(MyTSocket socket) {
		return new DefaultPooledObject<MyTSocket>(socket);
	}

	@Override
	public void destroyObject(PooledObject<MyTSocket> p) throws Exception {
		MyTSocket socket = p.getObject();
		socket.close();
		super.destroyObject(p);
	}

	@Override
	public boolean validateObject(PooledObject<MyTSocket> p) {
		MyTSocket t = p.getObject();
		Socket s = t.getSocket();
		boolean closed = s.isClosed();
		boolean connected = s.isConnected();
		boolean outputShutdown = s.isOutputShutdown();
		boolean inputShutdown = s.isInputShutdown();

		boolean urgentFlag = false;
		try {
			s.sendUrgentData(0xFF);
			urgentFlag = true;
		} catch (Exception e) {

		}

		return urgentFlag && connected && !closed && !inputShutdown && !outputShutdown && t.isAlive();
	}

}
